package com.jwdf.uda.ui.activity;
import android.Manifest;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jwdf.uda.R;
import com.jwdf.uda.app.AppContext;
import com.jwdf.uda.bean.PbBean;
import com.jwdf.uda.databinding.LayNewAnswerBinding;
import com.jwdf.uda.event.ImageSelectorEvent;
import com.jwdf.uda.photopicker.PhotoPickerActivity;
import com.jwdf.uda.runtime.PermissionRequest;
import com.jwdf.uda.runtime.RuntimePermission;
import com.jwdf.uda.ui.fragment.question.bean.EditDescribe;
import com.jwdf.uda.ui.fragment.question.bean.NewAnswer;
import com.jwdf.uda.utils.DisplayUtils;
import com.jwdf.uda.utils.EventBusUtil;
import com.jwdf.uda.view.dialog.AlertDialog;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import static com.jwdf.uda.bean.PbBean.PbSignBaseVoteOptionType.VOTE_OPTION_TYPE_A;
import static com.jwdf.uda.bean.PbBean.PbSignBaseVoteOptionType.VOTE_OPTION_TYPE_B;
import static com.jwdf.uda.bean.PbBean.PbSignBaseVoteOptionType.VOTE_OPTION_TYPE_C;
import static com.jwdf.uda.bean.PbBean.PbSignBaseVoteOptionType.VOTE_OPTION_TYPE_D;

/**
 * Created by fatsfan on 2016/11/11.
 */

public abstract class AnswerActivity extends AbsActivity {

    protected static final int PICK_PIC = 0;
    protected static int screeWidth, screeHeight;
    protected static String strQuesID = "id", strVoteCount = "size", strTitle = "title";
    private static int imageWidth, imageHeight;
    protected NewAnswer instance;
    protected LayNewAnswerBinding mBinding;
    protected View vSel, vVoteNone;
    protected int UPLOAD_NEW = 2, UPLOAD_EDIT = 3;
    /**
     * 把图片转成为bitmap，并且在富文本中显示的一个类
     */
    protected Html.ImageGetter imageGetter = new Html.ImageGetter() {
        @Nullable
        @Override
        public Drawable getDrawable(String source) {
            try {
                Bitmap bitmap = getImage(source);
                return getMyDrawable(bitmap);
            } catch(Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    };
    /**
     * 获得指定大小的bitmap
     *
     * @param bitmap
     *
     * @return
     */
    protected static Drawable getMyDrawable(Bitmap bitmap) {
        Drawable drawable = new BitmapDrawable(bitmap);
        float proportion = (float) screeWidth / imageWidth;
        float floatHeight = proportion * imageHeight;
        int intHeight = (int) (floatHeight + 0.5f);
        drawable.setBounds(0, 0, screeWidth, intHeight);
        return drawable;
    }
    /**
     * 通过这个方法对图片进行一定程度的压缩
     *
     * @param source
     *
     * @return
     */
    @Nullable
    protected Bitmap getImage(String source) {

        try {
            Bitmap bitmap;
            BitmapFactory.Options newOpts = new BitmapFactory.Options();
            newOpts.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(source), null, newOpts);
            newOpts.inJustDecodeBounds = false;
            imageWidth = newOpts.outWidth;
            imageHeight = newOpts.outHeight;

            // 缩放比,1表示不缩放
            int scale = 1;

            if(newOpts.outWidth > newOpts.outHeight && newOpts.outWidth > screeWidth) {
                scale = newOpts.outWidth / screeWidth;
            } else if(newOpts.outHeight > newOpts.outWidth && newOpts.outHeight > screeHeight) {
                scale = newOpts.outHeight / screeHeight;
            }
            newOpts.inSampleSize = scale * 2;// 设置缩放比例

            bitmap = BitmapFactory.decodeStream(new FileInputStream(source), null, newOpts);
            return bitmap;
        } catch(Exception e) {
            System.out.println("文件不存在");
            return null;
        }

    }

    @Override
    protected boolean fullScreenMode() {
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBusUtil.registerEvent(this);
        initViews();
        LinearLayout.LayoutParams flParams = (LinearLayout.LayoutParams) mBinding.rlAnswer.getLayoutParams();
        flParams.height += DisplayUtils.getStatusBarHeight(this);
        mBinding.rlAnswer.setLayoutParams(flParams);
        mBinding.tvHeadTitle.setPadding(0, DisplayUtils.getStatusBarHeight(this), 0, 0);
        mBinding.vBack.setPadding(DisplayUtils.dipToPix(this,15), DisplayUtils.getStatusBarHeight(this), DisplayUtils.dipToPix(this,15), 0);
        mBinding.tvHeadOperate.setPadding(DisplayUtils.dipToPix(this,15), DisplayUtils.getStatusBarHeight(this), DisplayUtils.dipToPix(this,15), 0);
    }
    abstract void initViews();
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBusUtil.unregisterEvent(this);
    }
    @PermissionRequest(100)
    protected void checkPermission() {
        String perms[] = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if(!RuntimePermission.hasPermissions(this, perms)) {
            RuntimePermission.requestPermissions(this, getString(R.string.app_name), 100, perms);
        }
    }
    /**
     * EditText竖直方向是否可以滚动
     *
     * @param editText 需要判断的EditText
     *
     * @return true：可以滚动   false：不可以滚动
     */
    protected boolean canVerticalScroll(EditText editText) {
        //滚动的距离
        int scrollY = editText.getScrollY();
        //控件内容的总高度
        int scrollRange = editText.getLayout().getHeight();
        //控件实际显示的高度
        int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() - editText.getCompoundPaddingBottom();
        //控件内容总高度与实际显示高度的差值
        int scrollDifference = scrollRange - scrollExtent;

        if(scrollDifference == 0) {
            return false;
        }

        return (scrollY > 0) || (scrollY < scrollDifference - 1);
    }
    protected void initVote(int voteCount) {

        if(voteCount == 0) {
            mBinding.layVote.setVisibility(View.GONE);
        } else {
            List<View> listVVote = new ArrayList<>();

            final TextView vVoteA = mBinding.vVoteA;
            final TextView vVoteB = mBinding.vVoteB;
            final TextView vVoteC = mBinding.vVoteC;
            final TextView vVoteD = mBinding.vVoteD;

            listVVote.add(vVoteA);
            listVVote.add(vVoteB);
            listVVote.add(vVoteC);
            listVVote.add(vVoteD);

            for(View item : listVVote)
                item.setVisibility(View.GONE);

            View.OnClickListener onClick = new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    vSel.setSelected(false);

                    if(v == vSel)
                        vSel = vVoteNone;
                    else {
                        switch(v.getId()) {
                            case R.id.vVoteA:
                                vSel = mBinding.vVoteA;
                                break;

                            case R.id.vVoteB:
                                vSel = mBinding.vVoteB;
                                break;

                            case R.id.vVoteC:
                                vSel = mBinding.vVoteC;
                                break;

                            case R.id.vVoteD:
                                vSel = mBinding.vVoteD;
                                break;
                        }

                        vSel.setSelected(true);
                    }

                }
            };

            for(int i = 0; i < voteCount; i++) {
                final View view = listVVote.get(i);
                view.setVisibility(View.VISIBLE);
                view.setOnClickListener(onClick);
            }

            if(vVoteA.getVisibility() == View.VISIBLE)
                vVoteA.setTag(VOTE_OPTION_TYPE_A);
            if(vVoteB.getVisibility() == View.VISIBLE)
                vVoteB.setTag(VOTE_OPTION_TYPE_B);
            if(vVoteC.getVisibility() == View.VISIBLE)
                vVoteC.setTag(VOTE_OPTION_TYPE_C);
            if(vVoteD.getVisibility() == View.VISIBLE)
                vVoteD.setTag(VOTE_OPTION_TYPE_D);

        }

    }
    protected void performClickVote(PbBean.PbSignBaseVoteOptionType vote) {

        switch(vote) {
            case VOTE_OPTION_TYPE_A:
                mBinding.vVoteA.performClick();
                break;
            case VOTE_OPTION_TYPE_B:
                mBinding.vVoteB.performClick();
                break;
            case VOTE_OPTION_TYPE_C:
                mBinding.vVoteC.performClick();
                break;
            case VOTE_OPTION_TYPE_D:
                mBinding.vVoteD.performClick();
                break;
        }
    }
    /**
     * 添加图片
     *
     * @param view
     */
    public void onImgAddClick(View view) {
        String perms[] = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if(RuntimePermission.hasPermissions(this, perms)) {
            PhotoPickerActivity.startActivity(this, PICK_PIC, new ArrayList<String>(), 9);
        } else {
            showAlertNotice();
        }
    }
    private void showAlertNotice() {
        final AlertDialog alertDialog = new AlertDialog(this, getString(R.string.permission_denied_msg), new AlertDialog.CallbackListener() {
            @Override
            public void clickYes() {

            }
        });
        alertDialog.show();
    }

    public void SaveDescribes(String describe, List<String> imageList) {
        NewAnswer.getInstance().deleteEditDescribeList();
        String content = describe;
        String[] mContent = content.split("￼");

        int startPosition;
        int i = 0;
        /**
         * 获得草稿的图片和文字信息，并把它展示出来
         */
        for(String string : mContent) {
            //LogUtils.d(string);
            EditDescribe editDescribe = new EditDescribe();
            if(!TextUtils.isEmpty(string)) {
                editDescribe.setDescribe(0);
                editDescribe.setmName(string);
                NewAnswer.getInstance().setEditDescribeList(editDescribe);
            }
            if(i != mContent.length - 1) {
                String mPicPath = imageList.get(i);
                editDescribe = new EditDescribe();
                editDescribe.setDescribe(1);
                editDescribe.setmUrl(mPicPath);
                NewAnswer.getInstance().setEditDescribeList(editDescribe);
                i++;
            }

        }
    }

    /**
     * 保持图片url
     */
    protected List<String> saveImage() {
        Editable eb = mBinding.et.getEditableText();
        String html = Html.toHtml(eb);
        int startIndex;
        int endIndex;
        List<String> imageList = new ArrayList<>();
        String[] mContentEb = html.split("\n");
        for(String string : mContentEb) {
            if(string.contains("jpg")) {
                startIndex = string.indexOf("src=") + 5;
                endIndex = string.lastIndexOf("jpg") + 3;
                String uri = string.substring(startIndex, endIndex);
                imageList.add(uri);
            } else {
                final String jpeg = "jpeg";
                if(string.contains(jpeg)) {
                    startIndex = string.indexOf("src=") + 5;
                    endIndex = string.lastIndexOf(jpeg) + jpeg.length();
                    String uri = string.substring(startIndex, endIndex);
                    imageList.add(uri);
                } else if(string.contains("png")) {
                    startIndex = string.indexOf("src=") + 5;
                    endIndex = string.lastIndexOf("png") + 3;
                    String uri = string.substring(startIndex, endIndex);
                    imageList.add(uri);
                }
            }
        }
        instance.setImageList(imageList);
        return imageList;
    }
    protected boolean Commitable() {
        int len = getLen();
        return len >= 3 && len <= 10000;
    }
    private int getLen() {
        List<EditDescribe> list2 = instance.getEditDescribeList();
        int len = 0;
        for(int i = 0; i < list2.size(); i++) {
            if(list2.get(i).getDescribe() == 0) {
                String value = list2.get(i).getmName().trim();
                len += value.length();
            }
        }
        return len;
    }
    protected boolean isContentLess() {
        return getLen() < 3;
    }
    protected boolean isContentMuch() {
        return getLen() > 10000;
    }
    protected void toastContentLess() {
        closeProgressDialog();
        Toast.makeText(AppContext.getInstance(), "文字必填，至少为3个字呦~~", Toast.LENGTH_LONG).show();
    }

    protected void toastContentMuch() {
        closeProgressDialog();
        Toast.makeText(AppContext.getInstance(), "字数太长，要在10000字以内哟~~", Toast.LENGTH_LONG).show();
    }

    //判断是否图片已经上传完成
    protected void doHasImageTokenSuccess(List<EditDescribe> list) {
        for(int i = 0; i < list.size(); i++) {
            if(list.get(i).getDescribe() == 1) {
                if(list.get(i).getToken().equals("")) {
                    return;
                }
            }
        }

        onPublished();
    }

    abstract void onPublished();

    protected List<PbBean.PbBaseReqDescription> getDescriptionList() {
        //        parsingDescribe(mBinding.editDescribe.getText().toString());
        List<PbBean.PbBaseReqDescription> descriptionList = new ArrayList<>();
        List<EditDescribe> list2 = instance.getEditDescribeList();
        for(int i = 0; i < list2.size(); i++) {
            if(list2.get(i).getDescribe() == 0) {
                PbBean.PbBaseReqDescription.Builder builder = PbBean.PbBaseReqDescription.newBuilder();
                builder.setDescType(PbBean.PbSignBaseDescriptionType.DESCRIPTION_TPYE_TEXT);
                String value = list2.get(i).getmName();

                //if(list2.get(i).getmName().equals("")) {
                //    value = "\n";
                //} else {
                //    value = value + "\n";
                //}

                builder.setDescription(value);
                descriptionList.add(builder.build());
            } else {
                PbBean.PbBaseReqDescription.Builder builder = PbBean.PbBaseReqDescription.newBuilder();
                builder.setDescType(PbBean.PbSignBaseDescriptionType.DESCRIPTION_TPYE_IMG);
                builder.setDescription(list2.get(i).getToken());
                descriptionList.add(builder.build());
            }
        }
        return descriptionList;
    }
    public void onEvent(ImageSelectorEvent event) {
        if(event.getCode() == 0) {
            switch(event.getType()) {
                case ImageSelectorEvent.EVENT_ADD:
                    for(int i = 0; i < event.getImages().size(); i++) {
                        final String url = event.getImages().get(i);
                        String urls = url.substring(7, url.length());
                        Editable eb = mBinding.et.getEditableText();
                        // 获得光标所在位置
                        int startPosition = mBinding.et.getSelectionStart();
                        eb.insert(startPosition, Html.fromHtml("<img src='" + urls + "'/><br/>", imageGetter, null));
                    }
                    break;
            }
        }
    }

}
